package com.hxexp.weixin.task.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import com.hxexp.weixin.constant.CacheName;
import com.hxexp.weixin.task.AccessTokenTimerTask;
import com.qq.weixin.constant.AppDevConstant;
import com.qq.weixin.mp.api.base.BaseAPI;
import com.qq.weixin.mp.api.base.model.AccessTokenBean;

/**
 * 定时刷新access_token任务接口实现类
 *
 * @author li.jiang
 */
// @Component
public final class AccessTokenTimerTaskImpl implements AccessTokenTimerTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenTimerTaskImpl.class);
    private static final String ACCESS_TOKEN_CACHE_KEY = "access_token";
    @Autowired
    private BaseAPI baseAPI;
    @Autowired
    private EhCacheCacheManager ehCacheManager;

    /**
     * 每隔7180秒刷新一次access_token
     *
     * @see <a href="http://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html">获取access token</a>
     */
    // @Scheduled(fixedDelay = 7180000)
    @Override
    public void refreshAccessToken() {
        String accessToken = "";
        boolean getAccessTokenIsSuccess = true;
        try {
            AccessTokenBean accessTokenBean = baseAPI.getAccessToken(AppDevConstant.HxExp.APPID, AppDevConstant.HxExp.APPSECRET);
            accessToken = accessTokenBean.getAccessToken();
            LOGGER.debug("当前的access_token: {}", accessToken);
        } catch (Exception e) {
            getAccessTokenIsSuccess = false;
            LOGGER.error("执行http请求发生异常！", e);
        }

        if (getAccessTokenIsSuccess) {
            Cache accessTokenCache = ehCacheManager.getCache(CacheName.ACCESS_TOKEN);
            accessTokenCache.put(ACCESS_TOKEN_CACHE_KEY, accessToken);
        }
    }

    /**
     * @return the accessToken
     */
    @Override
    public String getAccessToken() {
        Cache accessTokenCache = ehCacheManager.getCache(CacheName.ACCESS_TOKEN);
        return accessTokenCache.get(ACCESS_TOKEN_CACHE_KEY, String.class);
    }

}
